mod model;

use model::{ModelTodoItem, TodoManager, ModelPriority};
use slint::{Model, SharedString, VecModel};
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::path::PathBuf;
use chrono::{DateTime, Utc, TimeZone};

slint::include_modules!();

// 从模型优先级到UI优先级的转换
fn priority_model_to_slint(priority: &model::ModelPriority) -> slint_generatedTodoApp::Priority {
    match priority {
        model::ModelPriority::Low => slint_generatedTodoApp::Priority::Low,
        model::ModelPriority::Medium => slint_generatedTodoApp::Priority::Medium,
        model::ModelPriority::High => slint_generatedTodoApp::Priority::High,
    }
}

// 从UI优先级到模型优先级的转换
fn priority_slint_to_model(priority: &slint_generatedTodoApp::Priority) -> model::ModelPriority {
    match priority {
        slint_generatedTodoApp::Priority::Low => model::ModelPriority::Low,
        slint_generatedTodoApp::Priority::Medium => model::ModelPriority::Medium,
        slint_generatedTodoApp::Priority::High => model::ModelPriority::High,
    }
}

// 将日期时间从chrono::DateTime转换为字符串显示
fn format_datetime(datetime: &Option<DateTime<Utc>>) -> SharedString {
    match datetime {
        Some(dt) => SharedString::from(dt.format("%Y-%m-%d %H:%M").to_string()),
        None => SharedString::from(""),
    }
}

// 尝试将字符串解析为DateTime
fn parse_datetime(datetime_str: &str) -> Option<DateTime<Utc>> {
    if datetime_str.is_empty() {
        return None;
    }
    
    // 尝试解析日期时间字符串 (YYYY-MM-DD HH:MM)
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(datetime_str, "%Y-%m-%d %H:%M") {
        return Some(Utc.from_utc_datetime(&dt));
    }
    
    // 如果只输入了日期部分 (YYYY-MM-DD)
    if let Ok(date) = chrono::NaiveDate::parse_from_str(datetime_str, "%Y-%m-%d") {
        let dt = date.and_hms_opt(23, 59, 59).unwrap();
        return Some(Utc.from_utc_datetime(&dt));
    }
    
    None
}

// 定义从ModelTodoItem到slint::TodoItem的转换函数
fn model_to_slint(model_item: &ModelTodoItem) -> slint_generatedTodoApp::TodoItem {
    slint_generatedTodoApp::TodoItem {
        id: SharedString::from(&model_item.id),
        title: SharedString::from(&model_item.title),
        completed: model_item.completed,
        priority: priority_model_to_slint(&model_item.priority),
        due_date: format_datetime(&model_item.due_date),
    }
}

// 定义从slint::TodoItem到ModelTodoItem的转换函数
fn slint_to_model(slint_item: &slint_generatedTodoApp::TodoItem) -> ModelTodoItem {
    ModelTodoItem {
        id: slint_item.id.to_string(),
        title: slint_item.title.to_string(),
        completed: slint_item.completed,
        priority: priority_slint_to_model(&slint_item.priority),
        due_date: parse_datetime(&slint_item.due_date.to_string()),
    }
}

fn main() {
    // 创建数据文件路径
    let mut data_path = PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| ".".to_string()));
    data_path.push(".note_todo_data.json");
    
    // 初始化待办事项管理器
    let todo_manager = Arc::new(Mutex::new(TodoManager::new(data_path.to_str().unwrap())));
    
    // 创建UI
    let ui = TodoApp::new().unwrap();
    
    // 创建待办事项模型
    let todos_model = Rc::new(VecModel::default());
    
    // 初始化UI中的待办事项列表
    {
        let manager = todo_manager.lock().unwrap();
        for todo in manager.get_todos() {
            todos_model.push(model_to_slint(todo));
        }
    }
    
    // 设置UI中的待办事项模型
    ui.set_todos(todos_model.clone().into());
    
    // 处理添加待办事项
    let ui_handle = ui.as_weak();
    let manager_clone = todo_manager.clone();
    let todos_model_clone = todos_model.clone();
    ui.on_add_todo(move || {
        let ui = ui_handle.unwrap();
        let new_todo_text = ui.get_new_todo_text().to_string();
        let new_todo_priority = ui.get_new_todo_priority();
        let new_todo_due_date = ui.get_new_todo_due_date().to_string();
        
        if !new_todo_text.trim().is_empty() {
            let mut manager = manager_clone.lock().unwrap();
            let mut new_todo = manager.add_todo(
                &new_todo_text, 
                priority_slint_to_model(&new_todo_priority)
            );
            
            // 设置截止日期
            if !new_todo_due_date.trim().is_empty() {
                if let Some(due_date) = parse_datetime(&new_todo_due_date) {
                    manager.set_due_date(&new_todo.id, Some(due_date));
                    new_todo.due_date = Some(due_date);
                }
            }
            
            todos_model_clone.push(model_to_slint(&new_todo));
            
            ui.set_new_todo_text(SharedString::new());
            ui.set_new_todo_due_date(SharedString::new());
            // 保持优先级为用户选择的优先级，不重置为默认值
        }
    });
    
    // 处理切换待办事项完成状态
    let manager_clone = todo_manager.clone();
    let todos_model_clone = todos_model.clone();
    ui.on_toggle_todo(move |id| {
        let id_str = id.to_string();
        let mut manager = manager_clone.lock().unwrap();
        
        if manager.toggle_todo(&id_str) {
            for i in 0..todos_model_clone.row_count() {
                let todo = todos_model_clone.row_data(i).unwrap();
                if todo.id == id {
                    let mut updated_todo = todo.clone();
                    updated_todo.completed = !todo.completed;
                    todos_model_clone.set_row_data(i, updated_todo);
                    break;
                }
            }
        }
    });
    
    // 处理编辑待办事项
    let manager_clone = todo_manager.clone();
    let todos_model_clone = todos_model.clone();
    let ui_handle = ui.as_weak();
    ui.on_edit_todo(move |id, new_title| {
        let id_str = id.to_string();
        let new_title_str = new_title.to_string();
        
        let mut manager = manager_clone.lock().unwrap();
        let ui = ui_handle.unwrap();
        
        if manager.edit_todo(&id_str, &new_title_str) {
            for i in 0..todos_model_clone.row_count() {
                let todo = todos_model_clone.row_data(i).unwrap();
                if todo.id == id {
                    let mut updated_todo = todo.clone();
                    updated_todo.title = new_title;
                    todos_model_clone.set_row_data(i, updated_todo);
                    break;
                }
            }
        }
        
        // 编辑完成后重置编辑状态
        ui.set_current_edit_id(SharedString::new());
    });
    
    // 处理设置截止日期
    let manager_clone = todo_manager.clone();
    let todos_model_clone = todos_model.clone();
    ui.on_set_due_date(move |id, due_date_str| {
        let id_str = id.to_string();
        let due_date_str = due_date_str.to_string();
        
        let due_date = if due_date_str.trim().is_empty() {
            None
        } else {
            parse_datetime(&due_date_str)
        };
        
        let mut manager = manager_clone.lock().unwrap();
        
        if manager.set_due_date(&id_str, due_date) {
            for i in 0..todos_model_clone.row_count() {
                let todo = todos_model_clone.row_data(i).unwrap();
                if todo.id == id {
                    let mut updated_todo = todo.clone();
                    updated_todo.due_date = if due_date.is_some() {
                        format_datetime(&due_date)
                    } else {
                        SharedString::new()
                    };
                    todos_model_clone.set_row_data(i, updated_todo);
                    break;
                }
            }
        }
    });
    
    // 处理设置优先级
    let manager_clone = todo_manager.clone();
    let todos_model_clone = todos_model.clone();
    ui.on_set_priority(move |id, priority| {
        let id_str = id.to_string();
        let model_priority = priority_slint_to_model(&priority);
        
        let mut manager = manager_clone.lock().unwrap();
        
        if manager.set_priority(&id_str, model_priority) {
            for i in 0..todos_model_clone.row_count() {
                let todo = todos_model_clone.row_data(i).unwrap();
                if todo.id == id {
                    let mut updated_todo = todo.clone();
                    updated_todo.priority = priority;
                    todos_model_clone.set_row_data(i, updated_todo);
                    break;
                }
            }
        }
    });
    
    // 处理删除待办事项
    let manager_clone = todo_manager.clone();
    let todos_model_clone = todos_model.clone();
    ui.on_delete_todo(move |id| {
        let id_str = id.to_string();
        
        let mut manager = manager_clone.lock().unwrap();
        
        if manager.delete_todo(&id_str) {
            for i in 0..todos_model_clone.row_count() {
                let todo = todos_model_clone.row_data(i).unwrap();
                if todo.id == id {
                    todos_model_clone.remove(i);
                    break;
                }
            }
        }
    });
    
    // 处理开始编辑待办事项
    let ui_handle = ui.as_weak();
    ui.on_start_edit(move |id| {
        let ui = ui_handle.unwrap();
        ui.set_current_edit_id(id);
    });
    
    // 处理取消编辑
    let ui_handle = ui.as_weak();
    ui.on_cancel_edit(move || {
        let ui = ui_handle.unwrap();
        // 清空当前编辑ID，取消编辑状态
        ui.set_current_edit_id(SharedString::new());
    });
    
    // 运行UI
    ui.run().unwrap();
}
